import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;

class Solution {
    public int largestRectangleArea3n(int[] heights) {
        int n = heights.length;
        // 记录 i 左/右侧小于heights[i]的最近索引
        int[] left  = new int[n];
        int[] right  = new int[n];

        Deque<Integer> monoStack = new ArrayDeque<>(n);
        for (int i = 0; i < n; i++) {
            while (!monoStack.isEmpty() && heights[monoStack.peek()] >= heights[i]){
                monoStack.pop();
            }
            left[i] = monoStack.isEmpty()?-1:monoStack.peek();
            monoStack.push(i);
        }

        monoStack.clear();
        for (int i = n-1; i >= 0; i--) {
            while (!monoStack.isEmpty() && heights[monoStack.peek()] >= heights[i]){
                monoStack.pop();
            }
            right[i] = monoStack.isEmpty()?n:monoStack.peek();
            monoStack.push(i);
        }

        int ans = 0;
        // 遍历每个高度的矩形
        for (int j = 0; j < n; j++) {
            ans = Math.max(ans, (right[j] - left[j] - 1)*heights[j]);
        }
        return ans;
    }

    
    public int largestRectangleArea2n(int[] heights) {
        int n = heights.length;
        // 记录 i 左/右侧小于heights[i]的最近索引
        int[] left  = new int[n];
        int[] right  = new int[n];
        Arrays.fill(right, n);

        Deque<Integer> monoStack = new ArrayDeque<>(n);
        for (int i = 0; i < n; i++) {
            while (!monoStack.isEmpty() && heights[monoStack.peek()] >= heights[i]){
                // right本应是小于h[i]的右侧最近索引，此处是小于等于，故并非每个right[i]都正确，偏小
                // 但是对于最右侧的高为h[i]的元素，是正确的，能保证结果最大值一定会取到。
                right[monoStack.peek()] = i;
                monoStack.pop();
            }
            left[i] = monoStack.isEmpty()?-1:monoStack.peek();
            monoStack.push(i);
        }

        int ans = 0;
        // 遍历每个高度的矩形
        for (int j = 0; j < n; j++) {
            ans = Math.max(ans, (right[j] - left[j] - 1)*heights[j]);
        }
        return ans;
    }
}